/**
 * Created by Administrator on 2017/4/20.
 */


var Poker = require('../Poker/Poker');
var PokerRoom = require('../Poker/room').PokerRoom;

var Const = require('./const');
var SubCode = require('../subCode');
var GanDenYan = require('./rules');
var RoundStatus = {
    'WAITING': 1,   // 等待其它玩家准备
    'SELECTBASE': 2, //设置了基础分
    'READY': 3,     // 就绪，开始游戏
    'PLAY': 4,     // 玩家选牌
}

exports.GXGDYRoom = PokerRoom.extend({
    _roundStatus: RoundStatus.WAITING,

    _dealerIndex: 0,           // 庄家坐位
    _selectWaitTime: 0,        // 开始选牌的时间

    init: function (rid, creator, msg) {

        this._super(rid, creator, msg);

        this._roundStatus = RoundStatus.WAITING;
        GanDenYan.init();
        //局数
        // this.round = 0;
        // this.curRound = 0;
        //轮数
        this.turns = 1;
        this.lastPlayedCards = null;
        this.lastPlayerIndex = 0;

        this._dealerIndex = 0;

        this._BSMax = 0;
        this.sumBS = 1;

        this.winnerIndex = 0;
        this.settlement = false;

        var MS = this.getOption("BSFD");
        if (MS == 1) {
            this.MSMode = "FBFD";
            this._BSMax = this.getOption('rate');
        } else if (MS == 2) {
            this.MSMode = "BFB";
        }



    },
    reset: function () {
        this.turns = 1;
        this.lastPlayedCards = null;
        this.lastPlayerIndex = 0;
        this.winnerIndex = 0;
        this.sumBS = 1;
        this.settlement = false;

    },

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getRoundInfo: function () {
        var info = this._super();
        info.turns = this.turns;
        info.sumBS = this.sumBS;
        info.maxBS = this._BSMax;

        return info;
    },

    /**
     * 获取房间配置
     */
    getRoomConfig: function () {
        var cfg = this._super();
        cfg.respDestroyIgnore = 1;
        return cfg;
    },

    getReconnectInfo: function (rePlayer) {
        var info = this._super(rePlayer);
        info.dealer = this._dealerIndex;
        info.turns = this.turns;
        info.sumBS = this.sumBS;
        info.maxBS = this._BSMax;
        info.lastPlayerIndex = this.lastPlayerIndex;
        info.lastPlayCards = this.lastPlayedCards;
        return info;
    },

    onAfterPlayerReady: function (player) {

        var subConfig = this.getSubConfig();
        //检查是否开始游戏

        if (!this.isPlaying() && this.getReadyPlayerCount() >= subConfig.roomPlayerMin &&
            this.getPlayerCount() == this.getReadyPlayerCount()) {

            this._roundStatus = RoundStatus.READY
            //console.log("trystartNewRound")
            //this.tryStartNewRound();
            //}
        }
    },


    checkStartNewRound: function () {
        console.log("checccccccccck")
        if (this.isPlaying()) {
            console.log(this.isPlaying());
            console.log("isplaying")
            return false;
        }

        if (this._roundStatus != RoundStatus.READY) {
            console.log("no readdddy")
            return false;
        }
        console.log(0)
        return true;
    },
    //1
    onBeforeStartNewRound: function () {
        this._super();
        console.log(111111111)
    },
    //2
    onAfterStartNewRound: function () {
        this._super();
        console.log(2222222)
        this._startPlay();
    },

    onSettlement: function () {
        this._super();

        this.enumPlaying(function (eIndex, ePlayer) {
            ePlayer.settlementPattern();
        });

        this.enumPlaying(function (eIndex, ePlayer) {
            if (ePlayer.getRoundScore() > 0) {
                ePlayer.winSum += 1;
            } else if (ePlayer.getRoundScore() < 0) {
                ePlayer.defeatSum += 1;
            }
        });

    },

    onCurRoundFinished: function () {
        this._super();
        this._roundStatus = RoundStatus.WAITING;
        this.reset();
    },

    /******************************************************************
     * 功能接口
     ******************************************************************/

    handlePlayCards: function (player, msg, callback) {
        if (!msg.cards) {
            callback({ code: Code.ARGS_INVALID }); return;
        }

        if (!player.isPlaying()) {
            callback({ code: Code.PLAYER_NOT_PLAYING }); return;
        }

        if (!this.isPlaying()) {
            callback({ code: Code.ROOM_NOT_PLAYING }); return;
        }

        if (this.isCurRoundFinished()) {
            callback({ code: Code.ROOM_ROUND_FINISHED }); return;
        }

        var cards = msg.cards;
        if (!ExObject.isArray(cards)) {
            callback({ code: Code.ARGS_VALUE_WRONG }); return;
        }
        if (player.getIndex() != this.getCurPlay()) {
            callback({ code: Code.PLAYER_NOT_PLAYING }); return;
        }
        //对出的牌进行转换

        var objPattern = null;
        if (cards.length != 0) {
            objPattern = GanDenYan.getTypeWithVerifiedCards(cards);
        }

        if (objPattern) {
            if (objPattern.type == Const.Pattern.NONE) {
                console.log("dddandand")
                callback({ code: Code.ARGS_VALUE_WRONG }); return;
            }

            var cardsObj = player._handCards.getCards();
            var cardsArray = objPattern.cards.map(function (v) {
                return v['originValue'];
            });
            if (!cardsArray.every(function (v) {
                return cardsObj[v];
            })) {
                console.log("has not cards");
                callback({ code: Code.ARGS_VALUE_WRONG }); return;
            }

            if (this.lastPlayerIndex == 0 || this.lastPlayerIndex == this.getCurPlay()) {
                this._playCards(objPattern, player);
                if (this.settlement) {
                    callback({})
                    return;
                }
                this.lastPlayerIndex = player.getIndex();
                this._changeCurplayer(this.getNextPlayer(this.getCurPlay()));
            } else {
                //GanDenYan.compareCards(objPattern,this.lastPlayedCards)
                // console.log("compaarere")
                // console.log(objPattern)
                // console.log(this.lastPlayedCards);
                // console.log(GanDenYan.compareCards(objPattern, this.lastPlayedCards))
                if (this.lastPlayedCards && !GanDenYan.compareCards(objPattern, this.lastPlayedCards)) {
                    callback({ code: Code.ARGS_VALUE_WRONG }); return;
                }
                this._playCards(objPattern, player);
                if (this.settlement) {
                    callback({})
                    return;
                }
                this.lastPlayerIndex = player.getIndex();
                this._changeCurplayer(this.getNextPlayer(this.getCurPlay()));
            }

        } else {
            if (this.lastPlayerIndex == 0 || this.lastPlayerIndex == this.getCurPlay()) {
                var curPlayer = this.getPlayerByIndex(this.getCurPlay());
                var handCards = curPlayer._cardObjToArray(curPlayer._handCards.getCards());
                if (!(handCards.length == 1)) {
                    if (!(handCards[0] == Poker.SpecPoint.ANY || handCards[0] == Poker.SpecPoint.JOKER_B || handCards[0] == Poker.SpecPoint.JOKER_S)) {
                        callback({ code: Code.PLAYER_NOT_PLAYING }); return;
                    }
                    callback({ code: Code.PLAYER_NOT_PLAYING }); return;
                }
                //callback({ code: Code.PLAYER_NOT_PLAYING }); return;
            }
            this.broadcast("onPlayCards", {
                "playerIndex": player.getIndex(),
                "playCards": 0,
                "sumBS": this.sumBS
            });
            player.lastPlayCards = 0;
            this._changeCurplayer(this.getNextPlayer(this.getCurPlay()));
        }

        callback({})
        if (this.lastPlayerIndex == this.getCurPlay()) {
            if (!this.getPlayerByIndex(this.getCurPlay()).getCard()) {
                var flag = true;
                this.enumPlaying(function (eIndex, ePlayer) {
                    var handCards = ePlayer._cardObjToArray(ePlayer._handCards.getCards());
                    if (handCards.length == 1) {
                        if (handCards[0] == Poker.SpecPoint.ANY || handCards[0] == Poker.SpecPoint.JOKER_B || handCards[0] == Poker.SpecPoint.JOKER_S) {
                            return;
                        }
                    }
                    flag = false;
                });
                if (flag) {
                    this.winnerIndex = this._dealerIndex;
                    this.settlement = true;
                    this.settlementCurRound();
                    return;
                }
                // var curPlayer = this.getPlayerByIndex(this.getCurPlay());
                // var handCards = curPlayer._cardObjToArray(curPlayer._handCards.getCards());
                // if (handCards.length == 1) {
                //     if (handCards[0] == Poker.SpecPoint.ANY || handCards[0] == Poker.SpecPoint.JOKER_B || handCards[0] == Poker.SpecPoint.JOKER_S) {
                //         this.lastPlayedCards = 0;
                //         this.enumPlaying(function (eIndex, ePlayer) {
                //             ePlayer.lastPlayCards = -1;
                //         });
                //         this._changeCurplayer(this.getNextPlayer(this.getCurPlay()));
                //         return;
                //     }
                // }
            };
            this.lastPlayedCards = 0;
            this.enumPlaying(function (eIndex, ePlayer) {
                ePlayer.lastPlayCards = -1;
            });
            return;
        } else {
            this.getPlayerByIndex(this.getCurPlay()).send("onAddCard", {
                "cards": []
            });
        }

    },
    _playCards: function (objPattern, player) {
        var cardsArray = objPattern.cards.map(function (v) {
            return v['originValue'];
        });
        player.playCards(cardsArray);
        player.lastPlayCards = clone(objPattern);
        if (this.MSMode == "FBFD") {
            if (this._BSMax != 0) {
                this.sumBS *= Const.PatternMulti[objPattern.type];
                if (this.sumBS >= this._BSMax) {
                    this.sumBS = this._BSMax;
                }
            } else {
                this.sumBS *= Const.PatternMulti[objPattern.type];
            }
        }

        this.lastPlayedCards = objPattern;
        this.broadcast("onPlayCards", {
            "playerIndex": player.getIndex(),
            "playCards": objPattern,
            "sumBS": this.sumBS
        });

        if (objPattern.type >= Const.Pattern.THREEBOOM) {
            player.boomSum += 1;
        }
        if (player._handCards.isEmpty()) {
            this.winnerIndex = player.getIndex();
            this._dealerIndex = this.winnerIndex;
            this.settlement = true;
            this.settlementCurRound();
            return;
        }
    },
    _startPlay: function () {

        if (this._dealerIndex == 0) {
            // var arr = [];
            // this.enumPlaying(function (eIndex, ePlayer) {
            //     arr.push(eIndex);
            // });
            // this._dealerIndex = Ext.randArray(arr);
            this._dealerIndex = 1;
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });
            this._changeCurplayer(this._dealerIndex);
        } else {
            this.broadcastReplay("onDealerChanged", {
                dealer: this._dealerIndex,
            });
            this._changeCurplayer(this._dealerIndex);
        }

        this.initPlayersHandCards();
        //this._waitSelectBaseScore();
    },
    _changeCurplayer: function (playerIndex) {
        this.setCurPlay(playerIndex);
        this.broadcastReplay("onCurPlayer", {
            "playerIndex": this.getCurPlay(),
        });
    },

    //发一张牌
    popCard: function () {
        var card = 0;
        if (!this.getPublicCards().isEmpty()) {
            card = this.getPublicCards().getCard();
        }
        this._sendPublicCardChanged();
        return card;
    },

    handleGift: function (player, msg, callback) {
        if (isNaN(msg.targetIndex)) {
            callback({code: Code.ARGS_INVALID});
            return;
        }

        var gameConfig = this.getGameConfig();
        var giftType = msg.type;
        var giftConfig = gameConfig.Gift[giftType];
        if (!giftConfig) {
            callback({code: Code.ARGS_VALUE_WRONG});
            return;
        }

        var targetIndex = parseInt(msg.targetIndex);
        var targetPlayer = this.getPlayerByIndex(targetIndex);
        if (!targetPlayer) {
            callback({code: SubCode.INDEX_INVALID});
            return;
        }

        if (!player.checkResource(giftConfig.costs)) {
            callback({code: Code.LACK_OF_COIN});
            return;
        }

        this.broadcast("onPlayerGift", {
            playerIndex: player.getIndex(),
            targetIndex: targetIndex,
            type: giftType
        });
        callback();

        player.costResourceSync(giftConfig.costs);
        // targetPlayer.addResourceSync(giftConfig.harvest);
    },

    handleEnjoy: function (player, msg, callback) {
        callback();

        var gameConfig = this.getGameConfig();
        player.costResourceSync(gameConfig.Enjoy.costs);
    },
});